import re

import requests
from flask import current_app
from flask import request

from iHome import constants
from iHome import db
from iHome.utils.image_storage import storage_image
from . import api
from flask import g, jsonify
from iHome.models import User
from iHome.utils.response_code import RET
from iHome.utils.commons import login_required
import logging

@api.route('/users',methods=["GET"])
@login_required
def get_user_profile():
    """
    获取个人信息
    :return:
    """
    # 取到当前登录用户的 id
    user_id = g.user_id
    # 查询当前登录用户
    try:
        user = User.query.filter_by(id=user_id).first()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    # 如果用户不存在
    if user is None:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')

    return jsonify(errno=RET.OK, errmsg='OK', data=user.to_dict())

@api.route('/user/avatar',methods=["POST"])
@login_required
def upload_avatar():
    '''上传头像'''

    # 1.获取参数(上传的文件)
    try:
        avatar_file=request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.PARAMERR,errmsg="读取文件出错")

    # 2.把文件上传到七牛云
    try:
        image_name=storage_image(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.THIRDERR,errmsg="上传失败")

    # 3.更新头像信息并提交到数据库
    user_id = g.user_id
    try:
        User.query.filter_by(id=user_id).update({"avatar_url":image_name})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(error=RET.DBERR,errmsg="图片保存失败")


        # 4.返回上传的结果
    avatar_url = constants.QINIU_DOMIN_PREFIX + image_name
    return jsonify(errno=RET.OK, errmsg='图片上传成功', data={"avatar_url":avatar_url})
#
@api.route('/user/name', methods=['PUT'])
@login_required
def set_user_name():
    """
     设置用户名
    1.获取数据
    2.查询出指定user并提交到数据库
    3.返回修改结果
    """
    # 1.获取数据
    json_dict = request.get_json()
    name = json_dict['name']
    if name is None:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 2.查询出指定user并提交到数据库
    try:
        User.query.filter_by(id=g.user_id).update({'name': name})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='更新数据出错')
    else:
        # 3.返回修改结果
        return jsonify(errno=RET.OK, errmsg='修改成功')



@api.route('/user/auth', methods=['POST'])
@login_required
def set_auth():
    """
    实名认证
    """
    # 1.获取数据
    json_dict = request.get_json()
    real_name = json_dict['real_name']
    id_card = json_dict['id_card']
    if not all([real_name, id_card]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 查询身份证信息是否正确

    url = 'https://shenfen.supfree.net/search.asp?id={}'.format(id_card)

    data = requests.get(url)

    a = data.content.decode('gbk')

    b = re.findall('<tr><td width="162">原户籍地</td><td>(.*?)</td></tr>', a)
    if b:
        name = b[0].split()[0]
        if not real_name == name:
            return jsonify(errno=RET.DBERR, errmsg='归属地错误')
    else:
        return jsonify(errno=RET.DBERR, errmsg='认证失败')


    # 2.更新认证信息提交到数据库
    user_id = g.user_id
    try:
        User.query.filter_by(id=user_id).update({'real_name': real_name, 'id_card': id_card})
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='认证信息保存失败')
    else:
        return jsonify(errno=RET.OK, errmsg='认证信息保存成功')

@api.route('/user/auth')
@login_required
def get_auth():
    """
    获取用户实名认证信息

    """
    # 获取用户信息
    user_id = g.user_id
    try:
        user = User.query.filter_by(id=user_id).first()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    # 判空
    if user is None:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户不存在')

    return jsonify(errno=RET.OK, errmsg='OK', data=user.auth_to_dict())
